//table显示ID
var tableDiv = "tableHelpTestVODiv";
// 详情对话框
var detailDiv = "detailHelpTestVODiv";
// 表单DIV
var formDiv = "addHelpTestVOForm";
// 添加对话框
var addDlgDiv = "addHelpTestVODiv";
// 添加按钮
var addBtn = "HelpTestVOAddBtn";
// 新增按钮
var addDlgVO = "addHelpTestVO";
// 模糊搜索ID
var searchDiv = "searchHelpTestVOForm";

// 对象查询地址
var queryUrl = "../system/helpTestVO/queryHelpTestVOPageList";
// 对象增加地址
var addUrl = "../system/helpTestVO/saveHelpTestVO"
// 对象修改地址
var updateUrl = "../system/helpTestVO/updateHelpTestVOById"
// 对象删除地址
var deleteUrl = "../system/helpTestVO/deleteHelpTestVOById"
// 对象详情地址
var detailUrl = "../system/helpTestVO/queryHelpTestVOById"

// 数据显示dataTable
// var msgTable;
$(function() {

	// 初始化时间插件
	$(".ui_timepicke").datepicker({
		language : 'zh-CN',
		CustomFormat : "yyyy-mm-dd",
		minView : "month",
		changeYear : true,
		yearRange : "-200:+0",
		timepicker : false,
		todayBtn : true,
		autoclose : true
	});
	
	$.post('http://172.16.1.178:8080/bcAnalyzer/analyzer/analyzerAndTagging',{'str':'我想买个九十平的房子,两室一厅的,在南关区'},function(data){
		console.log(data);
	});

	// 显示帮助某行的详情
	$("#" + tableDiv + " tbody").on("click", "#HelpTestVOdetailDataBtn",
			function() {
				var pk = $(this).attr("data-id");
				$.post(detailUrl, {
					helpId : pk
				}, function(data) {
					showDetailData(data);
				});
			});

	// 显示详情对话框
	function showDetailData(data) {
		for ( var k in data) {
			var ele = $("#" + detailDiv + " #" + k + "Detail");
			ele.html(data[k]);
		}
		$("#" + detailDiv).modal("show");
	}
	;

	// 删除
	$("#" + tableDiv + " tbody").on("click", "#HelpTestVOdeleteDataBtn",
			function() {
				var pk = $(this).attr("data-id");
				confirm("您确定要删除此条信息吗 ?", function(isConfirm) {
					if (isConfirm) {
						$.post(deleteUrl, {
							helpId : pk
						}, function(data) {
							if (data != null && typeof (data) != "undefined") {
								if (data.flg == true) {
									swal("成功", "操作成功", "success");
								} else if (data.flg == true) {
									swal("失败", "操作失败", "error");
								}
							}
							reloadData();
						});

					} else {
						swal("取消", "您的操作已取消", "error");
					}
				});
			});

	var tabForm = $('#' + formDiv);
	var errorForm = $('.alert-error', tabForm);
	var successForm = $('.alert-success', tabForm);
	// 初始化表单-新增和删除
	function initFormValidate(param) {
		var url = "";
		if (param == "add") {
			url = addUrl;
		} else if (param == "update") {
			url = updateUrl;
		}
		$("#" + formDiv).attr("action", url);

		// 表单验证(新)
		$("#" + formDiv).validate(
				{
					errorElement : 'span', // default input error message
					// container
					errorClass : 'help-inline', // default input error message
					// class
					focusInvalid : false, // do not focus the last invalid
					// input
					ignore : "",
					rules : {        
						privateAlias : {
							required : true,
						},
						privatePwd : {
							required : true,
						},
						subject : {
							required : true,
						},
						consumerType : {
							required : true,
						},
						notBefore : {
							required : true,
						},
						notAfter : {
							required : true,
						},
						consumerAmount : {
							required : true,
						},
						info : {
							required : true,
						}
					},
					invalidHandler : function(event, validator) { // display
						// error
						// alert on
						// form
						// submit
						successForm.hide();
						errorForm.show();
						App.scrollTo(errorForm, -200);
					},
					highlight : function(element) { // hightlight error inputs
						$(element).closest('.help-inline').removeClass('ok'); // display
						// OK
						// icon
						$(element).closest('.control-group').removeClass(
								'success').addClass('error'); // set error
						// class to the
						// control group
					},
					unhighlight : function(element) { // revert the change
						// dony by hightlight
						$(element).closest('.control-group').removeClass(
								'error'); // set error class to the control
						// group
					},
					success : function(label) {
						label.addClass('valid').addClass('help-inline ok') // mark
						// the
						// current
						// input
						// as
						// valid
						// and
						// display
						// OK
						// icon
						label.closest('.control-group').removeClass('error')
								.addClass('success'); // set success class to
						// the control group
					},
					messages : {
						teacherName : {
							pattern : '必须是汉字'
						}
					},
					submitHandler : function(form) {
						successForm.show();
						errorForm.hide();
						valditFlag = true;// 防止重复录入
						tabForm.ajaxSubmit({
							type : "post",
							url : tabForm.attr("action"),
							success : function(data) {
								if (data.flg == true) {
									swal("成功", "操作成功", "success");
									$("#" + addDlgDiv).modal("hide");
									reloadData();
								} else if (data.flg == false) {
									swal("失败", "操作失败", "error");
									$("#" + addDlgDiv).modal("hide");
									reloadData();
								}

							}
						});
						return false;
					}
				});
		$('#helpIntime', '#' + formDiv).change(function() {
			$('#' + formDiv).validate().element($(this));
		})
	}

	// 新增按钮
	$("#" + addDlgVO).bind("click", function() {
		reset();
		$("#" + addBtn).text("保存");
		$("#" + formDiv + " #" + addBtn).attr("disabled", false);
		valditFlag = false;
		$("#" + addDlgDiv).modal("show");
		initFormValidate("add");
		
		tinymce.remove('#tinyTest02');
		
		$('#tinyTest02').val("");

		tinymce.init({
	        mode:"exact",
	        elements:"tinyTest02",
	        height: 400,
	        language: "zh_CN",
	        upload_image_ftpfileinput:"fileTinyMce",
	        plugins: [
	            'advlist autolink autosave lists link image charmap print preview anchor',
	            'searchreplace visualblocks code fullscreen textcolor colorpicker textpattern code uploadimage',
	            'contextmenu paste','emoticons'
	        ],
	        toolbar1: "undo redo | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | fontselect fontsizeselect ",
	        toolbar2: "forecolor backcolor | bullist numlist | outdent indent | removeformat | uploadimage | image | preview fullscreen | emoticons",
	        menubar: false
	    });
//		tinymce.activeEditor.setContent('<p>阿斯顿<span style="text-decoration: line-through;">发撒旦</span></p>');
	});
	
	// 新增数据保存按钮
	$("#" + addBtn).on("click", function() {
		console.log(tinyMCE.activeEditor.getContent());
		if (valditFlag) {
			return;
		}
		$('#' + formDiv).submit();
		resetRequired();
		reloadData();
	});

	// 修改
	$("#" + tableDiv + " tbody").on("click", "#HelpTestVOupdateDataBtn",
			function() {
				var pk = $(this).attr("data-id");
				$("." + formDiv + "_checktip").html("");
				reset();
				$("#" + addBtn).text("修改");
				$.ajax({
					url : detailUrl,
					data : {
						helpId : pk
					},
					type : "post",
					async : false,
					success : function(data) {
						if (data != null && typeof (data) != "undefined") {
							for ( var k in data) {
								var ele = $("#" + formDiv + " #" + k);
								ele.val(data[k]);
							}
							valditFlag = false;
							$("#" + addDlgDiv).modal("show");
							initFormValidate("update");
						}
					}
				});
				initFormValidate("update");
			});

	// 初始化表单
	function reset() {
		$("#" + formDiv).find("input").val("");
		$("#" + formDiv).find("select").val("");
		$(".help-inline").closest('.control-group').removeClass('ok');
		$(".help-inline").closest('.control-group').removeClass('error');
		$(".help-inline").closest('.control-group').removeClass('success');
		$(".help-inline").removeClass('ok');
		$(".help-inline").html('');
		$("br[name='br']").remove();
		$(".alert-success").attr("display", "none");
		$(".alert-error").attr("display", "none");
		$(".alert-error").attr("style", "");
		$(".alert-success").attr("style", "");
		$('#fileTinyMce').val("");
	}

	// 修改验证样式
	function resetRequired() {
	}

	$("#chooseCity").regionTree({
		// tree名字不可重复 默认:treeDemo
		name : 'cityTree',
		// 请求数据地址
		url : '../system/sysRegionVO/querySysRegionDataTree',
		// 控件显示级别 1(省),2(省市),3(省市县区) 默认:3级别
		level : "3",
		// 勾选类型 chkbox(单选),radio(多选)
		checkType : "radio",
		// 父节点 默认为1 用于控制起始节点
		parentId : "8",
		// 控件显示最小级别 0(国家),1(省),2(市),3(区) 用于控制仅显示吉林省下的全部区域
		minLevel : "3",
	// callBack: callBack,
	});
	$("#chooseCity1").regionTree({
		// 不可重复
		name : 'cityTree1',
		// 请求数据地址
		url : '../system/sysRegionVO/querySysRegionDataTree',
		// 级别 1(省),2(省市),3(省市县区)
		level : "3"
	});

	var dialogOpts = {
	   buttons: {
	      "Ok": function() { } ,
	      "Cancel": function() {}
	   }
	}
	
	$('#scBtn').on('click', function() {
		sendFileToFtp("file", "img", true, function(xhr) {
			if (xhr.readyState == 4 && xhr.status == 200) {  
				var data =JSON.parse(xhr.responseText);//data为上传成功后的返回值对象
				console.log(data)
				console.log(data.file);
				console.log(data.file.path);
			}
//			console.log(data.destination);
//			console.log(data.filename);
		})
		$("#tinyTest").dialog(dialogOpts);
	});

	tinymce.init({
        mode:"exact",
        elements:"tinyTest03",
        height: 400,
        language: "zh_CN",
        upload_image_ftpfileinput:"fileTinyMce",
        plugins: [
            'advlist autolink autosave lists link image charmap print preview anchor',
            'searchreplace visualblocks code fullscreen textcolor colorpicker textpattern code uploadimage',
            'contextmenu paste'
        ],
        toolbar1: "undo redo | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | fontselect fontsizeselect |Source code |",
        toolbar2: "forecolor backcolor | bullist numlist | outdent indent | removeformat | uploadimage | image | preview fullscreen ",
        menubar: false
    });
	
	//下载  
	$("#"+tableDiv+" tbody").on("click","#HelpTestVOdownLoadBtn",function(){
		var pk=$(this).attr("data-id");
		window.location="../system/helpTestVO/HelpTestCheckPrint";
	})
});

function reloadData() {
	var kk = $("#chooseCity1").attr("value");
	console.log(kk);
	msgTable.ajax.reload();
}
